export default {
  namespaced: true,
  state: {
    type: "all",
    list: JSON.parse(localStorage.getItem("list")) || [],
  },
  mutations: {
    //1.监听复选框是否被选中
    isChange(state, id) {
      const obj = state.list.find((item) => item.id === id);
      obj.isDone = !obj.isDone;
    },
    //2.删除按钮
    delList(state, id) {
      state.list = state.list.filter((item) => item.id !== id);
    },
    //3.单选->全选
    allChoose(state, check) {
      state.list.forEach((item) => (item.isDone = check));
    },
    //4.新增数据
    addList(state, content) {
      state.list.push({
        id: +new Date(),
        name: content,
        isDone: false,
      });
    },
    //7.清除所有已完成的任务
    clearAll(state) {
      state.list = state.list.filter((item) => !item.isDone);
    },
    //8.按钮的高亮效果
    changeType(state, type) {
      state.type = type;
    },
  },
  //7.延时一秒清除所有已完成的任务
  actions: {
    claerAsync(context) {
      setTimeout(() => {
        context.commit("clearAll");
      }, 1000);
    },
  },
  getters: {
    //5.显示未完成任务的数量
    length(state) {
      return state.list.filter((item) => !item.isDone).length;
    },
    //6.计算是否有已完成的任务
    isShow(state) {
      return state.list.some((item) => item.isDone);
    },
    //9.计算切换的按钮，对应显示的内容
    showList(state) {
      if (state.type === "active") {
        return state.list.filter((item) => !item.isDone);
      } else if (state.type === "complete") {
        return state.list.filter((item) => item.isDone);
      } else {
        return state.list;
      }
    },
  },
};
